#config.py
import yaml
from pathlib import Path
from nonebot import get_plugin_config, logger
from nonebot.plugin import PluginMetadata
from pydantic import BaseModel, Field
from typing import List

_current_dir = Path(__file__).parent.resolve()
CONFIG_PATH = _current_dir / "config.yml"  # 根据实际层级调整
# CONFIG_PATH = "./config.yml"  # 确保路径正确


def load_config():
    """从 config.yml 读取配置"""
    try:
        with open(CONFIG_PATH, "r", encoding="utf-8") as f:
            res = yaml.safe_load(f) or {}
            print("qwqqwqqwq!")
            logger.success(f"📦 配置文件 {CONFIG_PATH} 加载成功, 内容:{res}")
            return res
    except FileNotFoundError:
        logger.error(f"⚠️ 配置文件 {CONFIG_PATH} 未找到，使用默认配置")
        return {}
    except yaml.YAMLError as e:
        logger.error(f"⚠️ 配置文件解析失败: {e}")
        return {}

# 如果读文件失败就会fallback到这些硬编码的配置
class GroupMsgEnabledConfig(BaseModel):
    player_join: bool = True
    player_leave: bool = True
    player_msg: bool = True

class GroupMsgCustomizationConfig(BaseModel):
    player_join: str = "🎉🎉🎉 %PLAYER% 进入了神秘小服服！！✨✨✨"
    player_leave: str = "😢😢😢 %PLAYER% 暂时离开啦~呜——👋👋👋"
    player_msg: str = "🔈🔈🔈%PLAYER%在神秘小服服说:  %CONTENT%👀👀👀"


class Config(BaseModel):
    ws_server_url: str = Field(
        default="ws://localhost:8765", 
        description="WebSocket服务器地址"
    )
    target_groups: List[int] = Field(
        default=[259248174], 
        description="目标QQ群号列表"
    )
    source_groups: List[int] = Field(
        default=[259248174], 
        description="监听消息的QQ群号列表"
    )
    enable_private_report: bool = Field(
        default=False,
        description="是否启用私信报告WebSocket连接状态"
    )
    report_users: List[int] = Field(
        default=[1830540513],
        description="接收WebSocket连接状态私信的用户ID列表"
    )
    # 这个已在MCDR实现
    # forward_prefix: str = Field(
    #     default="!!",
    #     description="从MC到群的转发消息必须满足的前缀，满足转发，否则不转发"
    # )
    group_msg_enabled: GroupMsgEnabledConfig = Field(
        default=GroupMsgEnabledConfig(), 
        description="群消息启用配置"
    )
    group_msg_customization: GroupMsgCustomizationConfig = Field(
        default=GroupMsgCustomizationConfig(), 
        description="群消息自定义"
    )   

    @classmethod
    def from_yaml(cls):
        """从 YAML 文件初始化 Config，如果失败则使用硬编码默认值"""
        config_data = load_config()  # 读取 YAML
        try:
            return cls(**config_data)  # 使用 YAML 里的数据初始化
        except Exception as e:
            logger.error(f"⚠️ 配置项加载错误: {e}，回退到默认配置")
            return cls()  # 发生错误时使用默认配置
    
config_obj = Config.from_yaml()

__plugin_meta__ = PluginMetadata(
    name="MC服务器监控",
    description="通过WebSocket接收Minecraft服务器事件通知",
    usage="自动监听玩家加入/离开事件",
    config=Config,
    supported_adapters=["~onebot.v11"]
)